package com.dao.Impl;

import com.dao.NewsDao;
import com.entity.News;
import com.entity.PageBean;
import com.util.JDBC;
import com.util.TransBean;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class NewsDaoImpl implements NewsDao {

    @Override
    public void findAllNews(PageBean<News> pageBean) {
        String sql = "select count(*) from news where 1=1 %s ";
        String[] factor = pageBean.getFactor();
        String whereStr = "";
        if(factor!=null){
            for (int i = 0; i < factor.length; i++) {
                whereStr+=" and "+factor[i];
            }
        }
        sql = String.format(sql,whereStr);
        List<List> lists = JDBC.selectArray(sql);
        Integer count=null;
        if(lists!=null){
             count= ((Long) lists.get(0).get(0)).intValue();
        }
        sql = "select id,title,content,status,staffId,createdTime,endTime from news where 1=1 %s limit ?,?";
        sql = String.format(sql,whereStr);
        List<Map> maps = JDBC.selectMap(sql,(pageBean.getPageNo() - 1) * pageBean.getPageSize(),pageBean.getPageSize());
        pageBean.setData(TransBean.populate(News.class,maps));
        pageBean.setRowCount(count);
    }

    @Override
    public News findById(int id) {
        List<News> list = TransBean.populate(News.class, JDBC.selectMap("select id,title,content,status,staffId,createdTime,endTime" +
                " from news where id=?",id));
        if(list.size()>0){
            return list.get(0);
        }
       return null;
    }

    @Override
    public int update(News news) {
        return JDBC.sqlUpdate("update news set title=?,endTime=?,status=?,content=? where id=?",
        news.getTitle(),news.getEndTime(),news.getStatus(),news.getContent(),news.getId());
    }

    @Override
    public int detele(int id) {
        return JDBC.sqlUpdate("delete from news where id=?",id);
    }

    @Override
    public int insert(News news) {
        return JDBC.sqlInsert("insert into news(title,content,status,staffId,createdTime,endTime) values(?,?,?,?,?,?)",
                news.getTitle(),news.getContent(),news.getStatus(),news.getStaffId(),news.getCreatedTime(),news.getEndTime());
    }

    @Override
    public List<Map> findStatus() {
         return JDBC.selectMap("select id,title,content,status,staffId,createdTime,endTime from news where status=1 order by createdTime desc");
    }
}
